'use strict';

angular.module('afasApp')
  .controller('PaymentsCtrl', ['$scope', '$rootScope', 'Services', '$stateParams', '$state', '$filter', '$modal', '$locale', '_', function ($scope, $rootScope, Services, $stateParams, $state, $filter, $modal, $locale, _) {

    console.log(_);
    // console.log($filter);

    $scope.viewInvoice = true;
    // $scope.payments    = [];
    $scope.invoices = {
      'items': [],
      'isLoading': true
    };
    $scope.receipts = {
      'items': [],
      'isLoading': true
    };
    $scope.searchFor   = 'received_from';
    $scope.keyword     = '';
    $scope.errors = {};

    $scope.params = {
      'received_from'     : '',
      'transaction_number': '',
      // 'order_by': 'PaymentDate',
      'order_by': 'UpdatedAt',
      'order_type': 'DESC'
    };

    $scope.searchPayments = function() {
      $scope.params.received_from = '';
      $scope.params.transaction_number = '';
      $scope.params[$scope.searchFor] = $scope.keyword;
      resultInvoice(1);
      resultReceipt(1);
    };

    // PAGINATION
    $scope.pagesize = 10;

    $scope.invoices.pagination = {
      current: 1
    };

    $scope.receipts.pagination = {
      current: 1
    };

    $scope.pageInvoice = function(newPage) {
      resultInvoice(newPage);
    };

    function resultInvoice(pageNumber) {
      var data = {};
      $scope.invoices.isLoading = true;
      angular.copy($scope.params, data);
      data.paid = false;
      data.pagesize = $scope.pagesize;
      data.page = (pageNumber - 1);
      $scope.invoices.pagination.current = pageNumber;
      Services.getItems('payments', data)
      .then(function( results ) {
        var pagingData = angular.fromJson(results.headers['x-pagination']);
        $scope.invoices.totalItems = pagingData.TotalCount;
        $scope.invoices.items = results.data;
        $scope.invoices.isLoading = false;
      });
    };

    $scope.pageReceipt = function(newPage) {
      resultReceipt(newPage);
    };

    function resultReceipt(pageNumber) {
      var data = {};
      $scope.receipts.isLoading = true;
      angular.copy($scope.params, data);
      data.paid = true;
      data.pagesize = $scope.pagesize;
      data.page = (pageNumber - 1);
      $scope.receipts.pagination.current = pageNumber;
      Services.getItems('payments', data)
      .then(function( results ) {
        var pagingData = angular.fromJson(results.headers['x-pagination']);
        $scope.receipts.totalItems = pagingData.TotalCount;
        $scope.receipts.items = results.data;
        $scope.receipts.isLoading = false;
      });
    };

    $scope.searchPayments();

    $scope.getLabelFilter = function(value) {
      var data = [
        {
          'Query': 'received_from',
          'Label': 'Payer Name'
        },
        {
          'Query': 'transaction_number',
          'Label': 'Transaction Number'
        }
      ];
      data = _.findWhere(data, {'Query': value});
      return data.Label;
    };

    $scope.getLabelOrder = function(value) {
      var data = [
        {
          'Query': 'DESC',
          'Label': 'Newest First'
        },
        {
          'Query': 'ASC',
          'Label': 'Latest First'
        }
      ];
      data = _.findWhere(data, {'Query': value});
      return data.Label;
    };

  }])
  .controller('PaymentNewCtrl', ['$scope', '$rootScope', 'Services', '$filter', '$state', '$stateParams', '_', function ($scope, $rootScope, Services, $filter, $state, $stateParams, _) {

    // console.log($scope.selectedInvoice);
    $scope.payment = {
      'Invoices': []
    };
    $scope.newPayment  = {
      'BankTransfers'     : [],
      'CreditCardPayments': [],
      'TotalAmount'       : 0,
      'CashAmount'        : 0,
      'TotalPayment'      : 0,
      'TotalDiscount'     : 0,
      'Change'            : 0
    };
    $scope.Disc = {};
    $scope.Disc.params = {
      'include': 'discount_type'
    };
    $scope.BT = {};
    $scope.BT.params = {
      keyword: $scope.searchText
    };
    $scope.CC = {};
    $scope.CC.params = {
      keyword: $scope.searchText
    };
    $scope.PayMeths = $rootScope.PaymentMethods;
    $scope.bankTransfers = [];
    $scope.creditCards = [];
    $scope.discounts = [];
    $scope.psCredit = false;
    $scope.psBank = false;
    $scope.psDiscounts = false;
    $scope.currencies = [];
    $scope.creditcardtypes = [];
    $scope.BankPayment = 0;
    $scope.CCPayment = 0;
    $scope.payMethod = 0;
    $scope.selectedInvoice = {};

    Services.getItems($scope.CREDITCARDTYPE_URL)
    .then(function(results){
      $scope.creditcardtypes = results.data;
    });

    $scope.addCash = function() {
      $scope.newPayment.ForeignCurrencyPayments.push({
        'Amount': '',
        'Currency': {},
        'SerialNumber': ''
      });
    };

    $scope.removeCash = function(cash) {
      $scope.newPayment.ForeignCurrencyPayments = _.without($scope.newPayment.ForeignCurrencyPayments, cash);
    };

    Services.getItems('currencies')
    .then(function(results){
      $scope.currencies = results.data;
    });

    Services.getItem('payments', $stateParams.id, { 'include': 'all' })
    .then(function(results){
      $scope.payment = results.data;
      $scope.newPayment.TotalAmount += $scope.payment.TotalAmount;
      $scope.newPayment.TotalDiscount += $scope.payment.TotalDiscount;
      if ($scope.payment.PaymentStatus === 1) {
        $state.go( '^.list' );
      };
      if (!$scope.payment.PaymentDate) {
        $scope.newPayment.PaymentDate = new Date();
      } else {
        $scope.newPayment.PaymentDate = $scope.payment.PaymentDate;
      }
    });

    // $scope.$watch('payment.Invoices', function(newValue, oldValue) {
    //   // $scope.newPayment.Change = 0;
    //   console.log(newValue);
    //   var totalAmount = 0;
    //   var totalDiscount = 0;
    //   angular.forEach(newValue, function(value, index){
    //     var subtotalAmount = value.TotalAmount - value.TotalDiscount;
    //     totalAmount = totalAmount + subtotalAmount;
    //     totalDiscount = totalDiscount + value.TotalDiscount;
    //   });
    //   $scope.payment.TotalAmount = totalAmount;
    //   $scope.payment.TotalDiscount = totalDiscount;

    //   $scope.newPayment.Change = $scope.newPayment.TotalPayment - $scope.payment.TotalAmount;
    // }, true);

    $scope.$watch('newPayment.CashAmount', function(newValue, oldValue) {
      // $scope.newPayment.Change = 0;
      var BankTransfer = 0;
      var CreditCard = 0;
      var Cash = parseInt(newValue);
      if ($scope.newPayment.BankTransfers) {
        angular.forEach($scope.newPayment.BankTransfers, function(value, key){
          BankTransfer = BankTransfer + value.Amount;
        });
      };
      if ($scope.newPayment.CreditCardPayments) {
        angular.forEach($scope.newPayment.CreditCardPayments, function(value, key){
          CreditCard = CreditCard + value.Amount;
        });
      };
      $scope.newPayment.Change = (BankTransfer + CreditCard + Cash) - ($scope.payment.TotalAmount - $scope.payment.TotalDiscount);
      $scope.newPayment.TotalPayment = (BankTransfer + CreditCard + Cash);
    });

    $scope.$watchCollection('newPayment.BankTransfers', function(newValue, oldValue) {
      // $scope.newPayment.Change = 0;
      var BankTransfer = 0;
      var CreditCard = 0;
      var Cash = 0;

      angular.forEach(newValue, function(value, key){
        BankTransfer = BankTransfer + value.Amount;
      });
      $scope.BankPayment = BankTransfer;

      if ($scope.newPayment.CreditCardPayments) {
        angular.forEach($scope.newPayment.CreditCardPayments, function(value, key){
          CreditCard = CreditCard + value.Amount;
        });
      };
      if ($scope.newPayment.CashAmount) {
        Cash = parseInt($scope.newPayment.CashAmount);
      };
      $scope.newPayment.Change = (BankTransfer + CreditCard + Cash) - ($scope.payment.TotalAmount - $scope.payment.TotalDiscount);
      $scope.newPayment.TotalPayment = (BankTransfer + CreditCard + Cash);
    });

    $scope.$watchCollection('newPayment.CreditCardPayments', function(newValue, oldValue) {
      // $scope.newPayment.Change = 0;
      console.log(newValue);
      var BankTransfer = 0;
      var CreditCard = 0;
      var Cash = 0;
      if ($scope.newPayment.BankTransfers) {
        angular.forEach($scope.newPayment.BankTransfers, function(value, key){
          BankTransfer = BankTransfer + value.Amount;
        });
      };

      angular.forEach(newValue, function(value, key){
        CreditCard = CreditCard + value.Amount;
      });
      $scope.CCPayment = CreditCard;

      if ($scope.newPayment.CashAmount) {
        Cash = parseInt($scope.newPayment.CashAmount);
      };
      $scope.newPayment.Change = (BankTransfer + CreditCard + Cash) - ($scope.payment.TotalAmount - $scope.payment.TotalDiscount);
      $scope.newPayment.TotalPayment = (BankTransfer + CreditCard + Cash);
    });

    $scope.postPayment = function(){

      // console.log($scope.newPayment);

      // $scope.newPayment.Invoices = [];
      $scope.newPayment.PaymentMethods = [];
      if (!$scope.newPayment.hasOwnProperty('CashAmount')) {
        $scope.newPayment.CashAmount = 0;
      };
      if ($scope.newPayment.CashAmount < 1) {
        delete $scope.newPayment.Change;
        delete $scope.newPayment.CashAmount;
        // delete $scope.newPayment.ForeignCurrencyPayments;
      } else {
        $scope.newPayment.PaymentMethods.push(0);
      };
      if ($scope.newPayment.CreditCardPayments.length < 1) {
        delete $scope.newPayment.CreditCardPayments;
        // delete $scope.newPayment.ForeignCurrencyPayments;
      } else {
        $scope.newPayment.PaymentMethods.push(4);
        // $scope.newPayment.PaymentMethods.push(2);
      };
      if ($scope.newPayment.BankTransfers.length < 1) {
        delete $scope.newPayment.BankTransfers;
        // delete $scope.newPayment.ForeignCurrencyPayments;
      } else {
        // $scope.newPayment.PaymentMethods = [];
        $scope.newPayment.PaymentMethods.push(3);
      };
      $scope.newPayment.PaymentMethods = $scope.newPayment.PaymentMethods.join();
      $scope.newPayment.PaymentStatus = 1;
      $scope.newPayment.PaymentDate = $filter('date')($scope.newPayment.PaymentDate, 'yyyy-MM-dd');
      // angular.forEach($scope.payment.Invoices, function(value, key){
      //   // $scope.newPayment.Invoices.push({Id: value.Id});
      //   $scope.newPayment.TotalAmount += value.TotalAmount;
      //   $scope.newPayment.TotalDiscount += value.TotalDiscount;
      // });
      // console.log($scope.newPayment);

      Services.update('payments', $scope.newPayment, $scope.payment.Id)
      .then(function(results){
        $scope.payment = results.data;
        $state.go( '^.show.print', {id: $scope.payment.Id} );
      }, function(results){
        if (results.status == 400) {
          $scope.errors = results.data;

          if (typeof $scope.newPayment.CreditCardPayments === 'undefined' && $scope.newPayment.CreditCardPayments === null) {
            $scope.newPayment.CreditCardPayments = []
          };
          if (typeof $scope.newPayment.BankTransfers === 'undefined' && $scope.newPayment.BankTransfers === null) {
            $scope.newPayment.BankTransfers = []
          };
        }
      });
    };

    // PAGINATION
    $scope.pagesize = 5;

    $scope.BT.pagination = {
      current: 1
    };

    $scope.pageChangedBT = function(newPage) {
      getResultsPageBT(newPage);
    };

    function getResultsPageBT(pageNumber) {
      var data = $scope.BT.params;
      data.pagesize = $scope.pagesize;
      data.page = (pageNumber - 1);
      $scope.BT.pagination.current = pageNumber;
      Services.getItems('bank_transfers', data)
      .then(function( results ) {
        var pagingData = angular.fromJson(results.headers['x-pagination']);
        $scope.BT.totalItems = pagingData.TotalCount;
        $scope.bankTransfers = results.data;
      });
    };
    getResultsPageBT(1);

    $scope.checkSelected = function(Id) {
      return _.where($scope.newPayment.BankTransfers, { Id: Id }).length > 0;
    };

    $scope.removeTransfer = function(Id) {
      var item = _.findWhere($scope.newPayment.BankTransfers, {Id: Id});
      // return _.where($scope.newPayment.BankTransfers, { Id: Id }).length > 0;
      $scope.newPayment.BankTransfers = _.without($scope.newPayment.BankTransfers, item);
    };

    $scope.toggleSelection = function(bankTransfer) {
      var items = _.where($scope.newPayment.BankTransfers, {Id: bankTransfer.Id});
      var item = _.findWhere($scope.newPayment.BankTransfers, {Id: bankTransfer.Id});

      if (items.length > 0) {
        $scope.newPayment.BankTransfers = _.without($scope.newPayment.BankTransfers, item);
      } else {
        $scope.newPayment.BankTransfers.push(bankTransfer);
      }
    };

    $scope.removeTransferCC = function(Id) {
      var item = _.findWhere($scope.newPayment.CreditCardPayments, {Id: Id});
      // return _.where($scope.newPayment.CreditCardPayments, { Id: Id }).length > 0;
      $scope.newPayment.CreditCardPayments = _.without($scope.newPayment.CreditCardPayments, item);
    };

    $scope.addCC = function () {
      // console.log($scope.newItem);
      $scope.errors = {};
      Services.add($scope.CREDITCARDPAYMENT_URL, $scope.CC)
      .then(function(results){
        // console.log(results);
        $scope.CC = {};
        $scope.newPayment.CreditCardPayments.push(results.data);
        $scope.psCredit = false;
      }, function(results){
        if (results.status == 400) {
          $scope.errors = results.data;
        }
      });
    };

    $scope.removeCash = function(){
      delete $scope.newPayment.Change;
      delete $scope.newPayment.TotalPayment;
    };

    $scope.removeCC = function(){
      $scope.newPayment.CreditCardPayments = [];
    };

    $scope.removeBT = function(){
      $scope.newPayment.BankTransfers = [];
    };

    $scope.$watch('payMethod', function(newValue, oldValue){
      console.log(newValue);
      $scope.newPayment.BankTransfers = [];
      $scope.newPayment.CashAmount = 0;
      delete $scope.newPayment.CashAmount;
      $scope.newPayment.CreditCardPayments = [];
      if (newValue === 0) {
        $scope.PayMeths = _.filter($rootScope.PaymentMethods, function(obj) {
          return (obj.Id === 0 || obj.Id === 2);
        });
        // $scope.newPayment.BankTransfers = [];
      } else {
        $scope.PayMeths = _.filter($rootScope.PaymentMethods, function(obj) {
          return (obj.Id === 3);
        });
        // $scope.newPayment.CashAmount = 0;
        // delete $scope.newPayment.CashAmount;
        // $scope.newPayment.CreditCardPayments = [];
      }
    });

    // PAGINATION
    // $scope.pagesize = 5;

    $scope.Disc.pagination = {
      current: 1
    };

    $scope.pageChangedDisc = function(newPage) {
      getResultsPageDisc(newPage);
    };

    function getResultsPageDisc(pageNumber) {
      var data = $scope.Disc.params;
      data.pagesize = 10;
      data.page = (pageNumber - 1);
      $scope.Disc.pagination.current = pageNumber;
      Services.getItems('student_discounts', data)
      .then(function( results ) {
        var pagingData = angular.fromJson(results.headers['x-pagination']);
        $scope.Disc.totalItems = pagingData.TotalCount;
        $scope.discounts = results.data;
      });
    };
    getResultsPageDisc(1);

    $scope.manageDiscount = function(invoice){
      $scope.psDiscounts = true;
      $scope.selectedInvoice = invoice;
    };

    $scope.selectThisDiscount = function(discount){
      if (!discount.Percentage) {
        discount.Percentage = 0;
      };
      if (!discount.Amount) {
        discount.Amount = 0;
      };
      var disc = Math.abs(($scope.selectedInvoice.TotalAmount*(discount.Percentage/100))-discount.Amount);
      $scope.selectedInvoice.TotalDiscount = disc;
      $scope.psDiscounts = false;
    };
  }])
  .controller('PaymentCtrl', ['$scope', '$state', '$stateParams', '$filter', '_', function ($scope, $state, $stateParams, $filter, _) {

    console.log(_);
    console.log($filter);
    console.log($scope);
  }])
  .controller('PaymentSingleCtrl', ['$scope', '$timeout', '$rootScope', 'Services', '$state', '$stateParams', '$filter', '_', '$sce', function ($scope, $timeout, $rootScope, Services, $state, $stateParams, $filter, _, $sce) {

    // PRINTING

      function qzReady() {
        window["qz"] = document.getElementById('qz');
        if (qz) {
          try {
          } catch(err) {
            alert("ERROR:  \nThe applet did not load correctly.  Communication to the " +
              "applet has failed, likely caused by Java Security Settings.  \n\n" +
              "CAUSE:  \nJava 7 update 25 and higher block LiveConnect calls " +
              "once Oracle has marked that version as outdated, which " +
              "is likely the cause.  \n\nSOLUTION:  \n  1. Update Java to the latest " +
              "Java version \n          (or)\n  2. Lower the security " +
              "settings from the Java Control Panel.");
          }
        }
      }

      function notReady() {
        if (!isLoaded()) {
          return true;
        }
        else if (!qz.getPrinter()) {
          alert('Please select a printer first by using the "Detect Printer" button.');
          return true;
        }
        return false;
      }

      function isLoaded() {
        if (!qz) {
          alert('Error:\n\n\tPrint plugin is NOT loaded!');
          return false;
        } else {
          try {
            if (!qz.isActive()) {
              alert('Error:\n\n\tPrint plugin is loaded but NOT active!');
              return false;
            }
          } catch (err) {
            alert('Error:\n\n\tPrint plugin is NOT loaded properly!');
            return false;
          }
        }
        return true;
      }

      function qzDonePrinting() {
        if (qz.getException()) {
          alert('Error printing:\n\n\t' + qz.getException().getLocalizedMessage());
          qz.clearException();
          return;
        }

      // Alert success message
      // alert('Successfully sent print data to "' + qz.getPrinter() + '" queue.');
    }

    function findPrinter(name) {
      // var p = document.getElementById('printerHidden');
      // console.log(p);
      // if (name) {
      //   name = name;
      // }
      $scope.isPrintNotFound = true;

      if (isLoaded()) {
        var foundPrinter = qz.findPrinter(name);
        qz.findPrinter(name);
        if (typeof foundPrinter == 'undefined') {
          $scope.isPrintNotFound = true;
          var printers = qz.getPrinters();
          $timeout(function(){
            printers = qz.getPrinters();
            $scope.printers = printers.split(',');
          }, 1500);
        } else {
          $scope.isPrintNotFound = false;
        }
        window['qzDoneFinding'] = function() {
          var p = document.getElementById('printerHidden');
          var printer = qz.getPrinter();
          window['qzDoneFinding'] = null;
        };
      }
    }

    function printESCP(content) {
      if (notReady()) { return; }
      qz.append(content);
      qz.print();
      window['qzDoneAppending'] = null;
    }

    function printHTML(content) {
      if (notReady()) { return; }
      qz.appendHTMLFile("qz-print/form.html");
      while (!qz.isDoneAppending()) {
      // wait
      }
      qz.appendHTML(content);
      while (!qz.isDoneAppending()) {
      // wait
      }
      qz.printHTML();
    }

    function printToFile(content) {
      if (isLoaded()) {
        qz.findPrinter();

        window['qzDoneFinding'] = function() {
          // Send characters/raw commands to qz using "append"
          // Hint:  Carriage Return = \r, New Line = \n, Escape Double Quotes= \"
          qz.append(content);

          qz.printToFile("D:\\qz-print_test-print.txt");

          window['qzDoneFinding'] = null;
        };
      }
    }

    function putTabs(strRaw, tabs){
      var mod = Math.floor(strRaw.length/8);
      var tabChar = '';
      for (var i = 0; i < (tabs - mod); i++) {
        tabChar += '\t';
      };
      return strRaw + tabChar;
    }

    function putSpace(strRaw, space){
      var spaceChar = '';
      for (var i = 0; i < (space - (strRaw.length)); i++) {
        spaceChar += ' ';
      };
      return spaceChar + strRaw;
    }

    function chr(i) {
      return String.fromCharCode(i);
    }


    $scope.payment = {
      'BankTransfers'     : [],
      'CreditCardPayments': [],
      'TotalAmount'       : 0,
      'CashAmount'        : 0,
      'TotalPayment'      : 0,
      'TotalDiscount'     : 0,
      'Change'            : 0
    };
    var params = {
      'include': 'all,invoices,student'
    }
    $scope.PaymentMethodsArray = [];
    $scope.newPayment  = {
      'BankTransfers'     : [],
      'CreditCardPayments': [],
      'TotalAmount'       : 0,
      'CashAmount'        : 0,
      'TotalPayment'      : 0,
      'TotalDiscount'     : 0,
      'Change'            : 0
    };
    $scope.Disc = {};
    $scope.Disc.params = {
      'include': 'discount_type'
    };
    $scope.BT = {};
    $scope.BT.params = {
      keyword: $scope.searchText
    };
    $scope.CC = {};
    $scope.CC.params = {
      keyword: $scope.searchText
    };
    $scope.PayMeths = $rootScope.PaymentMethods;
    $scope.bankTransfers = [];
    $scope.creditCards = [];
    $scope.discounts = [];
    $scope.psCredit = false;
    $scope.psBank = false;
    $scope.psDiscounts = false;
    $scope.currencies = [];
    $scope.creditcardtypes = [];
    $scope.printers = [];
    $scope.printer = {
      'name': 'EPSON LX-310'
    };
    $scope.BankPayment = 0;
    $scope.CCPayment = 0;
    $scope.pay = {
      payMethod: 0
    };
    $scope.selectedInvoice = {};
    $scope.isPrintReady = true;
    $scope.isPrintNotFound = false;

    // setTimeout(function(){
    //   findPrinter($scope.printer.name);
    // }, 1000);

    Services.getItems($scope.CREDITCARDTYPE_URL)
    .then(function(results){
      $scope.creditcardtypes = results.data;
    });

    Services.getItem('payments', $stateParams.id, params)
    .then(function(results){
      $scope.payment = results.data;
      $scope.PaymentMethodsArray = $scope.payment.PaymentMethods.split(",");
      if ($scope.PaymentMethodsArray[0] == '3') {
        $scope.pay.payMethod = 1;
      };
      if (!$scope.payment.CreditCardPayments) {
        $scope.payment.CreditCardPayments = [];
      };
      if (!$scope.payment.PaymentDate) {
        $scope.payment.PaymentDate = new Date();
      };

      angular.forEach($scope.payment.Invoices, function (value, key) {
        Services.getItem('invoices', value.Id, {'include': 'all,student,payment,student_discounts'})
        .then(function(RDisc){
          console.log(RDisc.data);
          // value = {};
          value.StudentDiscounts = RDisc.data.StudentDiscounts;
          value.Enrollment = RDisc.data.Enrollment;
          value.PlacementTest = RDisc.data.PlacementTest;
          value.MakeUpTest = RDisc.data.MakeUpTest;
        });
      });
      $scope.isPrintReady = false;
      $scope.printURL = $sce.trustAsResourceUrl('/#/misc/payments/' + $scope.payment.Id + '/print');

      // console.log($scope.payment.Invoices);


      // console.log($scope.PaymentMethodsArray);
    });

    $scope.labelDiscount = function (discount, invoice) {
      return ((discount.Percentage) ? ((discount.Percentage/100) * invoice.TotalAmount) : 0 ) + ((discount.Amount) ? discount.Amount : 0 );
    }

    $scope.checkContain = function (value) {
      angular.forEach($scope.PaymentMethodsArray, function(val, key){
        if (val == value) {
          return true;
        };
      })
    };

    // $scope.$watch('payment.Invoices', function(newValue, oldValue) {
    //   // $scope.payment.Change = 0;
    //   console.log(newValue);
    //   var totalAmount = 0;
    //   var totalDiscount = 0;
    //   angular.forEach(newValue, function(value, index){
    //     var subtotalAmount = value.TotalAmount - value.TotalDiscount;
    //     totalAmount = totalAmount + subtotalAmount;
    //     totalDiscount = totalDiscount + value.TotalDiscount;
    //   });
    //   $scope.payment.TotalAmount = totalAmount;
    //   $scope.payment.TotalDiscount = totalDiscount;

    //   $scope.payment.Change = $scope.payment.TotalPayment - $scope.payment.TotalAmount;
    // }, true);


    $scope.$watch('pay.payMethod', function(newValue, oldValue){
      if ($state.current.name === 'payments.show.edit') {
        $scope.newPayment.BankTransfers = [];
        $scope.newPayment.CashAmount = 0;
        delete $scope.newPayment.CashAmount;
        $scope.newPayment.CreditCardPayments = [];
        if (newValue === 0) {
          $scope.PayMeths = _.filter($rootScope.PaymentMethods, function(obj) {
            return (obj.Id === 0 || obj.Id === 2);
          });
          // $scope.newPayment.BankTransfers = [];
        } else {
          $scope.PayMeths = _.filter($rootScope.PaymentMethods, function(obj) {
            return (obj.Id === 3);
          });
          // $scope.newPayment.CashAmount = 0;
          // delete $scope.newPayment.CashAmount;
          // $scope.newPayment.CreditCardPayments = [];
        }
      };
    });

    $scope.$watch('payment.CashAmount', function(newValue, oldValue) {
      // $scope.payment.Change = 0;
      if ($state.current.name === 'payments.show.edit') {
        var BankTransfer = 0;
        var CreditCard = 0;
        var Cash = parseInt(newValue);
        if ($scope.payment.BankTransfers) {
          angular.forEach($scope.payment.BankTransfers, function(value, key){
            BankTransfer = BankTransfer + value.Amount;
          });
        };
        if ($scope.payment.CreditCardPayments) {
          angular.forEach($scope.payment.CreditCardPayments, function(value, key){
            CreditCard = CreditCard + value.Amount;
          });
        };
        $scope.payment.Change = (BankTransfer + CreditCard + Cash) - ($scope.payment.TotalAmount - $scope.payment.TotalDiscount);
        $scope.payment.TotalPayment = (BankTransfer + CreditCard + Cash);
      };
    });

    $scope.$watchCollection('payment.BankTransfers', function(newValue, oldValue) {
      // $scope.payment.Change = 0;
      if ($state.current.name === 'payments.show.edit') {
        var BankTransfer = 0;
        var CreditCard = 0;
        var Cash = 0;

        angular.forEach(newValue, function(value, key){
          BankTransfer = BankTransfer + value.Amount;
        });
        $scope.BankPayment = BankTransfer;

        if ($scope.payment.CreditCardPayments) {
          angular.forEach($scope.payment.CreditCardPayments, function(value, key){
            CreditCard = CreditCard + value.Amount;
          });
        };
        if ($scope.payment.CashAmount) {
          Cash = parseInt($scope.payment.CashAmount);
        };
        $scope.payment.Change = (BankTransfer + CreditCard + Cash) - ($scope.payment.TotalAmount - $scope.payment.TotalDiscount);
        $scope.payment.TotalPayment = (BankTransfer + CreditCard + Cash);
      };
    });

    $scope.$watchCollection('payment.CreditCardPayments', function(newValue, oldValue) {
      // $scope.payment.Change = 0;
      if ($state.current.name === 'payments.show.edit') {
        console.log(newValue);
        var BankTransfer = 0;
        var CreditCard = 0;
        var Cash = 0;
        if ($scope.payment.BankTransfers) {
          angular.forEach($scope.payment.BankTransfers, function(value, key){
            BankTransfer = BankTransfer + value.Amount;
          });
        };

        angular.forEach(newValue, function(value, key){
          CreditCard = CreditCard + value.Amount;
        });
        $scope.CCPayment = CreditCard;

        if ($scope.payment.CashAmount) {
          Cash = parseInt($scope.payment.CashAmount);
        };
        $scope.payment.Change = (BankTransfer + CreditCard + Cash) - ($scope.payment.TotalAmount - $scope.payment.TotalDiscount);
        $scope.payment.TotalPayment = (BankTransfer + CreditCard + Cash);
      };
    });

    $scope.postPayment = function(){

      console.log($scope.payment);

      // $scope.payment.Invoices = [];
      $scope.payment.PaymentMethods = [];
      if (!$scope.payment.hasOwnProperty('CashAmount')) {
        $scope.payment.CashAmount = 0;
      };
      if ($scope.payment.CashAmount < 1) {
        delete $scope.payment.Change;
        delete $scope.payment.CashAmount;
        // delete $scope.payment.ForeignCurrencyPayments;
      } else {
        $scope.payment.PaymentMethods.push(0);
      };
      if ($scope.payment.CreditCardPayments.length < 1) {
        delete $scope.payment.CreditCardPayments;
        // delete $scope.payment.ForeignCurrencyPayments;
      } else {
        $scope.payment.PaymentMethods.push(4);
      };
      if ($scope.payment.BankTransfers.length < 1) {
        delete $scope.payment.BankTransfers;
        // delete $scope.payment.ForeignCurrencyPayments;
      } else {
        $scope.payment.PaymentMethods.push(3);
      };
      $scope.payment.PaymentMethods = $scope.payment.PaymentMethods.join();
      $scope.payment.PaymentStatus = 0;
      $scope.payment.PaymentDate = $filter('date')($scope.payment.PaymentDate, 'yyyy-MM-dd');
      // angular.forEach($scope.payment.Invoices, function(value, key){
      //   // $scope.payment.Invoices.push({Id: value.Id});
      //   $scope.payment.TotalAmount += value.TotalAmount;
      //   $scope.payment.TotalDiscount += value.TotalDiscount;
      // });
      // console.log($scope.payment.PaymentMethods);

      Services.update('payments', $scope.payment, $scope.payment.Id)
      .then(function(results){
        $scope.payment = results.data;
        $state.go( '^.show.print', {id: $scope.payment.Id} );
      }, function(results){
        if (results.status == 400) {
          $scope.errors = results.data;

          if (typeof $scope.payment.CreditCardPayments === 'undefined' && $scope.payment.CreditCardPayments === null) {
            $scope.payment.CreditCardPayments = []
          };
          if (typeof $scope.payment.BankTransfers === 'undefined' && $scope.payment.BankTransfers === null) {
            $scope.payment.BankTransfers = []
          };
        };

      });
    };

    // PAGINATION
    $scope.pagesize = 5;

    $scope.BT.pagination = {
      current: 1
    };

    $scope.pageChangedBT = function(newPage) {
      getResultsPageBT(newPage);
    };

    function getResultsPageBT(pageNumber) {
      var data = $scope.BT.params;
      data.pagesize = $scope.pagesize;
      data.page = (pageNumber - 1);
      $scope.BT.pagination.current = pageNumber;
      Services.getItems('bank_transfers', data)
      .then(function( results ) {
        var pagingData = angular.fromJson(results.headers['x-pagination']);
        $scope.BT.totalItems = pagingData.TotalCount;
        $scope.bankTransfers = results.data;
      });
    };
    getResultsPageBT(1);

    $scope.checkSelected = function(Id) {
      return _.where($scope.payment.BankTransfers, { Id: Id }).length > 0;
    };

    $scope.removeTransfer = function(Id) {
      var item = _.findWhere($scope.payment.BankTransfers, {Id: Id});
      // return _.where($scope.payment.BankTransfers, { Id: Id }).length > 0;
      $scope.payment.BankTransfers = _.without($scope.payment.BankTransfers, item);
    };

    $scope.toggleSelection = function(bankTransfer) {
      var items = _.where($scope.payment.BankTransfers, {Id: bankTransfer.Id});
      var item = _.findWhere($scope.payment.BankTransfers, {Id: bankTransfer.Id});

      if (items.length > 0) {
        $scope.payment.BankTransfers = _.without($scope.payment.BankTransfers, item);
      } else {
        $scope.payment.BankTransfers.push(bankTransfer);
      }
    };

    $scope.removeTransferCC = function(Id) {
      var item = _.findWhere($scope.payment.CreditCardPayments, {Id: Id});
      // return _.where($scope.payment.CreditCardPayments, { Id: Id }).length > 0;
      $scope.payment.CreditCardPayments = _.without($scope.payment.CreditCardPayments, item);
    };

    $scope.addCC = function () {
      // console.log($scope.newItem);
      $scope.errors = {};
      Services.add($scope.CREDITCARDPAYMENT_URL, $scope.CC)
      .then(function(results){
        // console.log(results);
        $scope.CC = {};
        $scope.payment.CreditCardPayments.push(results.data);
        $scope.psCredit = false;
      }, function(results){
        if (results.status == 400) {
          $scope.errors = results.data;
        }
      });
    };

    $scope.removeCash = function(){
      delete $scope.payment.Change;
      delete $scope.payment.TotalPayment;
    };

    $scope.removeCC = function(){
      $scope.payment.CreditCardPayments = [];
    };

    $scope.removeBT = function(){
      $scope.payment.BankTransfers = [];
    };

    $scope.printESCP = function(){
      findPrinter($scope.printer.name);
      var lineAmount = 10;
      var actualLine = 0;
      var content = chr(15);
      content += $scope.payment.TransactionNumber;
      // content += '\t\t\t\t\t\t\t\t\t\t\t\t\t\t' + 'I / A / L / F';
      content += '\r\n';
      actualLine++;
      content += '\r\n';
      actualLine++;
      // content += '\t\t\t\t\t\t\t\t\t\t\t\t\t\t' + 'Education for Development';
      // content += '\r\n';
      // content += '\r\n';
      // content += '\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t' + 'Jl Raya Sesetan 190';
      // content += '\r\n';
      // content += '\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t' + '    Denpasar - Bali 80223 Indonesia';
      // content += '\r\n';
      // content += '\t\t\t\t\t\t\t\t\t\t\t\t\t\t' + '     Tel: + 62 - 361-225243; Fax: + 62 - 361-263509';
      // content += '\r\n';
      content += 'Date: ' + $filter('date')($scope.payment.PaymentDate, 'dd/MM/yyyy');
      // content += '\t\t\t\t\t\t\t\t\t\t\t\t\t\t' + '   ialfbali@ialf.edu | www.ialf.edu';
      // content += '\r\n';
      // content += '\r\n';
      // content += '\t\t\t\t\t\t\t\t' + 'RECEIPT';
      // content += '\r\n';
      // content += '\t' + 'Student' + '\t\t\t\t\t\t\t\t' + 'Item' + '\t\t\t\t\t\t' + 'Qty' + '\t\t\t' + 'Total';
      content += '\r\n';
      actualLine++;
      content += '\r\n';
      actualLine++;

      var inc = 1;
      angular.forEach($scope.payment.Invoices, function(value, key){
        content += inc + '\t';
        var firstVal = '';
        var secondVal = '';
        var sID = '';

        switch(value.InvoiceType){
          case 0:
            firstVal += value.PlacementTest.Student.FullName;
            sID += value.PlacementTest.Student.SID;
            secondVal += $filter('date')(value.PlacementTest.DateTime, 'medium');
            break;
          case 1:
            firstVal += value.Enrollment.Student.FullName;
            sID += value.Enrollment.Student.SID;
            secondVal += value.Enrollment.CourseSchedule.CourseName;
            break;
          case 2:
            firstVal += value.Enrollment.Student.FullName;
            sID += value.Enrollment.Student.SID;
            secondVal += value.MakeUpTest.Type + $filter('date')(value.MakeUpTest.MakeUpTestSchedule.DateTime, 'medium');
            break;
          case 3:
            firstVal += value.Refund.Enrollment.Student.FullName;
            sID += value.Refund.Enrollment.Student.SID;
            secondVal += value.Refund.Enrollment.CourseSchedule.CourseName;
            break;
          case 4:
            firstVal += value.Enrollment.Student.FullName;
            sID += value.Enrollment.Student.SID;
            secondVal += value.Enrollment.CourseSchedule.CourseName;
            break;
        }
        content += putTabs(firstVal, 4);
        content += putTabs(secondVal, 8);

        content += '1' + '\t';
        content += 'Rp' + '\t';
        content += putSpace($filter('currency')(value.TotalAmount, '', 0), 15);

        content += '\r\n';
        actualLine++;
        content += '\t' + sID + '\t\t\t';

        angular.forEach(value.StudentDiscounts, function(valB, keyB){
          var label = valB.Number + valB.SourceReference;
          var amount = '(' + $filter('currency')($scope.labelDiscount(valB, value), '', 0);
          content += putTabs(label, 8);
          content += '1' + '\t';
          content += 'Rp' + '\t';
          content += putSpace(amount, 15) + ')';
          content += '\r\n';
          actualLine++;
          content += '\t\t\t\t\t';
        });

        // content += 'Total Amount' + '\t\t\t\t\t\t\t\t';
        // content += 'Rp' + '\t';
        // content += putSpace($filter('currency')((value.TotalAmount - value.TotalDiscount), '', 0), 15);
        content += '\r\n';
        actualLine++;

        inc++;
      });

      content += '\r\n';
      actualLine++;
      content += '\t\t\t\t\t\t\t\t\t\t\t\t\t\t' + '------------------------';
      content += '\r\n';
      actualLine++;
      content += '\t\t\t\t\t\t\t\t\t\t\t\t\t' + 'Total' + '\t' + 'Rp' + '\t';
      content += putSpace($filter('currency')(($scope.payment.TotalAmount - $scope.payment.TotalDiscount), '', 0), 15);

      content += '\r\n';
      actualLine++;
      content += '\t\t\t\t\t\t\t\t\t\t\t\t\t' + 'Payment';
      content += '\r\n';
      actualLine++;
      content += '\t\t\t\t\t\t\t\t\t\t\t\t\t' + 'Cash' + '\t' + 'Rp' + '\t';
      content += putSpace('(' + $filter('currency')(($scope.payment.CashAmount), '', 0), 15) + ')';
      content += '\r\n';
      actualLine++;

      angular.forEach($scope.payment.BankTransfers, function(value, key){
        content += '\t\t\t\t\t\t\t\t\t\t\t\t' + value.RefNumber + '\t' + 'Rp' + '\t';
        content += putSpace('(' + $filter('currency')((value.Amount), '', 0), 15) + ')';
        content += '\r\n';
        actualLine++;
      });

      angular.forEach($scope.payment.CreditCardPayments, function(value, key){
        content += '\t\t\t\t\t\t\t\t\t\t\t\t' + value.CardNumber + '\t' + 'Rp' + '\t';
        content += putSpace('(' + $filter('currency')((value.Amount), '', 0), 15) + ')';
        content += '\r\n';
        actualLine++;
      });

      content += '\t\t\t\t\t\t\t\t\t\t\t\t\t\t' + '------------------------';
      content += '\r\n';
      actualLine++;
      content += '\t\t\t\t\t\t\t\t\t\t\t\t\t' + 'Change' + '\t' + 'Rp' + '\t';
      content += putSpace($filter('currency')(($scope.payment.Change), '', 0), 15);

      content += '\r\n';
      actualLine++;
      var word = '*' + $filter('inWords')(($scope.payment.TotalAmount - $scope.payment.TotalDiscount)) + ' rupiah';
      content += '\t\t\t\t\t\t' + putSpace(word, 88);
      actualLine++;

      var lineRest = lineAmount - (actualLine % lineAmount);
      for (var i = 1; i <= lineRest; i++) {
        content += '\r\n';
      };

      content += chr(15);

      setTimeout(function(){
        // printToFile(content);
        printESCP(content);
      }, 1000);
    };

    // $scope.printHTML = function(){
    //   findPrinter($scope.printer.name);
    //   // var inPaymentHTML = document.getElementById('print-payment-iframe').innerHTML;

    //   setTimeout(function(){
    //     // printHTML(inPaymentHTML);
    //     $("#print-payment-iframe").html2canvas({
    //       canvas: hidden_screenshot,
    //       onrendered: function() {
    //         qz.append64($("canvas")[0].toDataURL('image/png'));
    //         qz.printPS();
    //       }
    //     });
    //   }, 1000);
    // };

    $scope.printToFile = function(){
      findPrinter($scope.printer.name);

      setTimeout(function(){
        printToFile(content);
      }, 1000);
    };

  }]);